package models

import (
	"encoding/json"
)

type Chain struct {
	Values   []interface{}     `json:"values"`
	Children map[string]*Chain `json:"children"`
}

func NewChain() *Chain {
	return &Chain{
		Values:   make([]interface{}, 0),
		Children: make(map[string]*Chain),
	}
}

func (m *Chain) Add(value interface{}, paths ...string) {
	cur := m
	for _, path := range paths {
		if cur.Children[path] != nil {
			cur = cur.Children[path]
		} else {
			nc := NewChain()
			cur.Children[path] = nc
			cur = nc
		}
	}
	cur.Values = append(cur.Values, value)
}

func (c *Chain) MarshalJson() (d string, err error) {
	b, err := json.Marshal(c)
	d = string(b)
	return
}
